package com.bestv.search.management.command;

import com.bestv.search.common.dataSource.DataSourceKey;
import com.bestv.search.common.model.Site;
import com.bestv.search.common.model.SysRole;
import com.bestv.search.common.model.SysUser;
import com.bestv.search.common.model.UserExistsException;
import com.bestv.search.common.service.SiteManager;
import com.bestv.search.common.service.SysRoleManager;
import com.bestv.search.common.service.SysUserManager;
import com.bestv.search.common.util.CommandException;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class UserCommand {

    protected final Log log = LogFactory.getLog(getClass());
    private SysUserManager userManager;
    private SiteManager siteManager;
    private SysRoleManager roleManager;

    public SiteManager getSiteManager() {
        return siteManager;
    }

    public void setSiteManager(SiteManager siteManager) {
        this.siteManager = siteManager;
    }

    public String save(SysUser user, Map<String, String[]> map, DataSourceKey dsKey) throws CommandException {
        String[] id = map.get("id");
        String[] username = map.get("username");
        String[] loginName = map.get("loginName");
        String[] email = map.get("email");
        String[] password = map.get("password");
        String[] siteId = map.get("site");
        String[] roleId = map.get("roleId");
        String[] phone = map.get("phone");
        String[] enabled = map.get("enable");

        if (loginName[0].trim().length() == 0) {
            return "{'result':'failure','message':'loginName'}";
        }

        if (password[0].trim().length() == 0) {
            return "{'result':'failure','message':'password'}";
        }

        Site site = siteManager.getSiteById(dsKey, new Long(siteId[0]));

        if (site == null) {
            return "{'result':'failure','message':'site'}";
        }

        if (roleId == null || roleId.length == 0) {
            return "{'result':'failure','message':'role'}";
        }

        SysUser existUser = null;
        try {
            existUser = userManager.getUserByLoginName(dsKey, loginName[0]);
        } catch (UsernameNotFoundException e) {
            existUser = null;
        }
        if (existUser != null) {
            // if update
            if (!"".equals(id[0])) {
                if (existUser.getId() != new Long(id[0]).longValue()) {
                    return "{'result':'failure','message':'exist'}";
                }
            } else {
                return "{'result':'failure','message':'exist'}";
            }
        }

        SysUser userObj = null;
        if ("".equals(id[0])) {
            userObj = new SysUser();
            userObj.setUsername(username[0]);
            userObj.setId(0L);// 表示是new操作，供后续使用
        } else {
            userObj = userManager.getUserById(dsKey, new Long(id[0]));
        }
        userObj.getRoles().clear();
        for (int i = 0; i < roleId.length; i++) {
            SysRole role = roleManager.getRoleByID(dsKey, new Long(roleId[i]));
            if (role != null)
                userObj.getRoles().add(role);
        }
        userObj.setLoginName(loginName[0]);
        userObj.setEmail(email[0]);
        userObj.setPassword(password[0]);
        userObj.setSite(site);
        userObj.setPhoneNumber(phone[0]);
        userObj.setUsername(username[0]);
        if ("true".equals(enabled[0]))
            userObj.setEnable(true);
        else
            userObj.setEnable(false);
        try {
            userManager.saveUser(dsKey, userObj);
        } catch (UserExistsException e) {
            // log.error(e);
            // throw new CommandException();
            return "{'result':'failure','message':'exist'}";
        }

        return "{'result':'success','message':''}";
    }

    public String get(SysUser user, Map<String, String[]> map, DataSourceKey dsKey) throws CommandException {
        String result = "";
        String[] id = (String[]) map.get("id");

        SysUser userObj = userManager.getUserById(dsKey, new Long(id[0]));
        try {
            JSONObject jsonObject = userToJson(userObj);
            List<JSONObject> roles = new ArrayList<JSONObject>();
            Iterator<SysRole> iterator = userObj.getRoles().iterator();
            while (iterator.hasNext()) {
                SysRole role = iterator.next();
                JSONObject roleJson = new JSONObject();
                roleJson.put("id", role.getId());
                roles.add(roleJson);
            }
            JSONArray roleArray = new JSONArray(roles.toArray());
            jsonObject.put("roles", roleArray);
            result = jsonObject.toString();
        } catch (JSONException e) {
            log.error(e);
            throw new CommandException();
        }
        return result;
    }

    public SysRoleManager getRoleManager() {
        return roleManager;
    }

    public void setRoleManager(SysRoleManager roleManager) {
        this.roleManager = roleManager;
    }

    public String changePassword(SysUser user, Map<String, String[]> map, DataSourceKey dsKey) {
        System.out.println("changePassword.....");
        String[] password = map.get("newPassword");
        user.setPassword(password[0]);
        System.out.println(password[0]);
        System.out.println(user.getPassword());

        try {
            userManager.saveUser(dsKey, user);
        } catch (UserExistsException e) {
            // log.error(e);
            // throw new CommandException();
            return "{'result':'failure','message':'rechangePwd'}";
        }
        return "{'result':'success','message':''}";
    }

    public String delete(SysUser user, Map<String, String[]> map, DataSourceKey dsKey) throws CommandException {
        String[] id = map.get("id");

        try {
            SysUser existUser = userManager.getUserById(dsKey, new Long(id[0]));
            existUser.setEnable(false);
            userManager.saveUser(dsKey, existUser);
        } catch (UsernameNotFoundException e) {
            throw new CommandException();
        } catch (UserExistsException e) {
            throw new CommandException();
        }

        return "{'result':'success','message':''}";
    }

    public String find(SysUser user, Map<String, String[]> map, DataSourceKey dsKey) throws CommandException {
        String result = "";

        List<SysUser> users = userManager.getUsers(dsKey);
        List<JSONObject> list = new ArrayList<JSONObject>();
        try {
            for (SysUser u : users) {
                list.add(userToJson(u));
            }
            JSONArray jsonArray = new JSONArray(list.toArray());
            result = "{'users':" + jsonArray.toString() + "}";
        } catch (JSONException e) {
            log.error(e);
            throw new CommandException();
        }

        return result;
    }

    public SysUserManager getUserManager() {
        return userManager;
    }

    public void setUserManager(SysUserManager userManager) {
        this.userManager = userManager;
    }

    private JSONObject userToJson(SysUser user) throws JSONException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", user.getId());
        jsonObject.put("loginName", user.getLoginName());
        jsonObject.put("username", user.getUsername());
        jsonObject.put("site", user.getSite().getName());
        jsonObject.put("email", user.getEmail());
        jsonObject.put("phone", user.getPhoneNumber());
        jsonObject.put("enable", user.isEnable());
        jsonObject.put("password", user.getPassword());
        jsonObject.put("siteId", user.getSite().getId());
        return jsonObject;
    }
}
